package com.wsk.tool;

import com.baidu.aip.imagecensor.AipImageCensor;
import com.wsk.tool.entity.Baidu;
import org.json.JSONObject;

import javax.imageio.stream.FileImageInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @DESCRIPTION :
 * @AUTHOR : WuShukai1103
 * @TIME : 2017/12/31  13:37
 */
@Deprecated
public class Sample {
    //设置APPID/AK/SK
    public static final String APP_ID = "10608004";
    public static final String API_KEY = "AXwR2FvqCinmL1rxPDeLZF7N";
    public static final String SECRET_KEY = "9SuYaXw5mttPo2O05i42VDCOiAyudInt";

    public static void main(String[] args) {
        // 初始化一个AipImageCensor
        AipImageCensor client = new AipImageCensor(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

//        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
//        client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
//        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 调用接口
        String path = "D:\\image\\CG63dcCaGZhCkWpqEhFF2017-01-17.jpg";
        JSONObject res = client.antiPorn(path);
        System.out.println(res.toString(2));
        Baidu baidu = com.alibaba.fastjson.JSONObject.parseObject(res.toString(2), Baidu.class);
        System.out.println(baidu.getConclusion());
        System.out.println(baidu.toString());

//        sample(client);

    }

    public static void sample(AipImageCensor client) {
        // 参数为本地图片路径
        String path = "D:\\image\\dVRtcwvY53WpL6sVfsjP20170115.jpg";
//        JSONObject response = client.imageCensorUserDefined(path, EimgType.FILE, null);
//        System.out.println(response.toString());

        // 参数为url
//        String url = "http://testurl";
//        response = client.imageCensorUserDefined(url, EimgType.URL, null);
//        System.out.println(response.toString());

//        // 参数为本地图片文件二进制数组
        byte[] file = image2byte(path);
        JSONObject response = client.imageCensorUserDefined(file, null);
        System.out.println(response.toString());
    }
    //图片到byte数组
    public static byte[] image2byte(String path){
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        }
        catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        }
        catch (IOException ex1) {
            ex1.printStackTrace();
        }
        return data;
    }
}
